package com.xsd.xsdhouduan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xsd.xsdhouduan.common.Result;
import com.xsd.xsdhouduan.entity.Admin;
import com.xsd.xsdhouduan.entity.PlatformIncome;
import com.xsd.xsdhouduan.entity.School;
import com.xsd.xsdhouduan.entity.Task;
import com.xsd.xsdhouduan.entity.User;
import com.xsd.xsdhouduan.service.AdminService;
import com.xsd.xsdhouduan.service.PlatformIncomeService;
import com.xsd.xsdhouduan.service.SchoolService;
import com.xsd.xsdhouduan.service.TaskService;
import com.xsd.xsdhouduan.service.UserService;
import com.xsd.xsdhouduan.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin
public class AdminController {
    
    @Autowired
    private AdminService adminService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private SchoolService schoolService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PlatformIncomeService platformIncomeService;
    
    /**
     * 获取管理员信息
     */
    @GetMapping("/info")
    public Result<Admin> getAdminInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String account = jwtUtil.getUsernameFromToken(token);
            Admin admin = adminService.getByAccount(account);
            if (admin != null) {
                return Result.success(admin);
            }
        }
        return Result.error("获取管理员信息失败");
    }
    
    /**
     * 获取所有用户
     */
    @GetMapping("/users")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsersWithDetails();
        return Result.success(users);
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/users/{userId}/status")
    public Result<String> updateUserStatus(@PathVariable Long userId, @RequestParam Integer status) {
        User user = userService.getById(userId);
        if (user != null) {
            user.setStatus(status);
            if (userService.updateById(user)) {
                return Result.success("更新成功");
            }
        }
        return Result.error("更新失败");
    }
    
    /**
     * 更新用户余额
     */
    @PutMapping("/users/{userId}/balance")
    public Result<String> updateUserBalance(@PathVariable Long userId, @RequestParam Double amount) {
        if (userService.updateBalance(userId, amount)) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    
    /**
     * 获取所有学校
     */
    @GetMapping("/schools")
    public Result<List<School>> getAllSchools() {
        List<School> schools = schoolService.list();
        return Result.success(schools);
    }
    
    /**
     * 添加学校
     */
    @PostMapping("/schools")
    public Result<String> addSchool(@RequestBody School school) {
        if (schoolService.save(school)) {
            return Result.success("添加成功");
        }
        return Result.error("添加失败");
    }
    
    /**
     * 更新学校状态
     */
    @PutMapping("/schools/{schoolId}/status")
    public Result<String> updateSchoolStatus(@PathVariable Long schoolId, @RequestParam Integer status) {
        School school = schoolService.getById(schoolId);
        if (school != null) {
            school.setStatus(status);
            if (schoolService.updateById(school)) {
                return Result.success("更新成功");
            }
        }
        return Result.error("更新失败");
    }
    
    /**
     * 更新学校信息
     */
    @PutMapping("/schools/{schoolId}")
    public Result<String> updateSchool(@PathVariable Long schoolId, @RequestBody School school) {
        school.setId(schoolId);
        if (schoolService.updateById(school)) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    
    /**
     * 删除学校
     */
    @DeleteMapping("/schools/{schoolId}")
    public Result<String> deleteSchool(@PathVariable Long schoolId) {
        if (schoolService.removeById(schoolId)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
    
    /**
     * 获取所有任务
     */
    @GetMapping("/tasks")
    public Result<List<Task>> getAllTasks() {
        List<Task> tasks = taskService.getAllTasksWithDetails();
        return Result.success(tasks);
    }
    
    /**
     * 根据学校获取任务
     */
    @GetMapping("/tasks/school/{schoolId}")
    public Result<List<Task>> getTasksBySchool(@PathVariable Long schoolId) {
        List<Task> tasks = taskService.getBySchoolId(schoolId);
        return Result.success(tasks);
    }
    
    /**
     * 删除任务
     */
    @DeleteMapping("/tasks/{taskId}")
    public Result<String> deleteTask(@PathVariable Long taskId) {
        if (taskService.removeById(taskId)) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
    
    /**
     * 关闭任务
     */
    @PutMapping("/tasks/{taskId}/close")
    public Result<String> closeTask(@PathVariable Long taskId) {
        Task task = taskService.getById(taskId);
        if (task != null && task.getStatus() != 1) {
            task.setStatus(1); // 已关闭
            if (taskService.updateById(task)) {
                return Result.success("关闭成功");
            }
        }
        return Result.error("关闭失败");
    }
    
    /**
     * 获取数据统计概览
     */
    @GetMapping("/dashboard/stats")
    public Result<Map<String, Object>> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总用户数
        long totalUsers = userService.count();
        stats.put("totalUsers", totalUsers);
        
        // 总任务数
        long totalTasks = taskService.count();
        stats.put("totalTasks", totalTasks);
        
        // 合作学校数
        long totalSchools = schoolService.count();
        stats.put("totalSchools", totalSchools);
        
        // 平台收入统计
        BigDecimal totalPlatformIncome = platformIncomeService.getTotalIncome();
        List<PlatformIncome> pendingIncomes = platformIncomeService.getPendingSettlement();
        List<PlatformIncome> settledIncomes = platformIncomeService.getSettledIncome();
        
        stats.put("totalPlatformIncome", totalPlatformIncome);
        stats.put("pendingIncomes", pendingIncomes.size());
        stats.put("settledIncomes", settledIncomes.size());
        
        return Result.success(stats);
    }
    
    /**
     * 获取最近任务
     */
    @GetMapping("/dashboard/recent-tasks")
    public Result<List<Task>> getRecentTasks(@RequestParam(defaultValue = "5") int limit) {
        List<Task> recentTasks = taskService.getRecentTasks(limit);
        return Result.success(recentTasks);
    }
    
    /**
     * 获取最近用户
     */
    @GetMapping("/dashboard/recent-users")
    public Result<List<User>> getRecentUsers(@RequestParam(defaultValue = "5") int limit) {
        List<User> recentUsers = userService.getRecentUsers(limit);
        return Result.success(recentUsers);
    }
    
    /**
     * 获取待结算收入列表
     */
    @GetMapping("/income/pending")
    public Result<List<PlatformIncome>> getPendingIncome() {
        List<PlatformIncome> incomes = platformIncomeService.getPendingSettlement();
        Result<List<PlatformIncome>> result = Result.success(incomes);
        System.out.println("DEBUG: AdminController.getPendingIncome - 查询到待结算收入数量: " + incomes.size());
        System.out.println("DEBUG: AdminController.getPendingIncome - 返回Result对象: " + result);
        return result;
    }
    
    /**
     * 获取已结算收入列表
     */
    @GetMapping("/income/settled")
    public Result<List<PlatformIncome>> getSettledIncome() {
        List<PlatformIncome> incomes = platformIncomeService.getSettledIncome();
        Result<List<PlatformIncome>> result = Result.success(incomes);
        System.out.println("DEBUG: AdminController.getSettledIncome - 查询到已结算收入数量: " + incomes.size());
        System.out.println("DEBUG: AdminController.getSettledIncome - 返回Result对象: " + result);
        return result;
    }
    
    /**
     * 结算收入
     */
    @PostMapping("/income/{incomeId}/settle")
    public Result<String> settleIncome(@PathVariable Long incomeId) {
        System.out.println("DEBUG: AdminController.settleIncome - 开始结算收入ID: " + incomeId);
        boolean result = platformIncomeService.settleIncome(incomeId);
        System.out.println("DEBUG: AdminController.settleIncome - 结算结果: " + result);
        if (result) {
            return Result.success("结算成功");
        }
        return Result.error("结算失败");
    }
    
    /**
     * 获取平台总收入
     */
    @GetMapping("/income/total")
    public Result<BigDecimal> getTotalIncome() {
        BigDecimal totalIncome = platformIncomeService.getTotalIncome();
        return Result.success(totalIncome);
    }
}
